package com.mcb.autopublish.demos.web.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.mcb.autopublish.demos.web.po.ResponseResult;
import com.mcb.autopublish.demos.web.vo.AiNews;
import com.mcb.autopublish.demos.web.vo.ResultHotspot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

/**
 * <p>
 *
 * </p>
 *
 * @author mcb
 * @since 2024/6/5
 */
public class CommonUtils {

    private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);


    private static final String BASE_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String GRANT_TYPE = "client_credential";
    private static final String APPID_Placeholder = "APPID";
    private static final String APPSECRET_Placeholder = "APPSECRET";


    /**
     * 通过Url地址获取信息内容
     *
     * @param urlCommon method
     * @return
     */
    public static String getUrlConstants(String urlCommon, String method, String content) {
        logger.info("开始请求地址开始，地址为：{}", urlCommon);
        String result = "";
        try {
            URL url = new URL(urlCommon);  // 人工智能
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setDoOutput(true);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(content.getBytes());
            outputStream.flush();
            outputStream.close();
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder tianapi = new StringBuilder();
            String temp = null;
            while (null != (temp = bufferedReader.readLine())) {
                tianapi.append(temp);
            }
            result = tianapi.toString();
            logger.info("请求地址结束，返回结果为：{}", result);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * JSON解析
     *
     * @throws IOException
     */
    public static List<AiNews> parseJson(String jsonString) throws IOException {
        logger.info("开始解析热点话题");
        ObjectMapper mapper = new ObjectMapper();
        // 将整个JSON字符串映射到ResponseResult对象
        ResponseResult<ResultHotspot> response = mapper.readValue(jsonString, new TypeReference<ResponseResult<ResultHotspot>>() {
        });
        List<AiNews> newsList = new ArrayList<>();
        if (response.getCode() == 200) {
            ResultHotspot resultHotspot = response.getResult();
            // 将newslist部分映射到List<AiNews>
            newsList = resultHotspot.getNewslist().stream()
                    .map(item -> mapper.convertValue(item, AiNews.class))
                    .collect(Collectors.toList());
            // 现在newsList包含了所有的新闻条目
            logger.info("下面是获取到的热点信息：");
            for (AiNews news : newsList) {
                logger.info("标题：{}", news.getTitle());
                logger.info("描述：{}", news.getDescription());
            }
        } else {
            System.out.println("请求失败，错误信息：" + response.getMsg());
        }
        return newsList;
    }

    /**
     * 获取微信access_token
     *
     * @return
     */
    public static String getWeChatAccessToken() {

        String result = "";
        try {
            // 替换APPID和APPSECRET为实际的值
            String appId = "wxa0f56a6f041bf71a";
            String appSecret = "2202f1693459d03527a6bbddfb156a70";

            URL url = new URL(BASE_URL + "?grant_type=" + GRANT_TYPE + "&appid=" + appId + "&secret=" + appSecret);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 默认情况下，HttpURLConnection会自动跟随重定向，这里保持默认即可
            // 如果服务器需要身份验证或其他特殊处理，可能需要设置额外的头信息

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                result = response.toString();
            } else {
                System.err.println("Failed with response code: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 通义千问接口获取数据
     */
    public static GenerationResult getDataByTongYiQianWen(String content) throws Exception {
        String resultData = "";
        Generation gen = new Generation();

        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();

        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(content)
                .build();

        GenerationParam param = GenerationParam.builder()
                .model("qwen-turbo")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .build();

        return gen.call(param);
    }


    /**
     * 获取微信公众号accessToken的参数
     * @return
     */
    public static String getAccessTokenArgs() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("grant_type", "client_credential");
        jsonObject.addProperty("appid", "wxa0f56a6f041bf71a");
        jsonObject.addProperty("secret", "2202f1693459d03527a6bbddfb156a70");
        return jsonObject.toString();
    }


    /**
     *  获取Json中某一个节点的值
     * @return
     * @throws IOException
     */
    public static String getJsonNode(String jsonString, String nodeName) throws IOException {
        String result = "";
        try {
            // 创建 ObjectMapper 对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 解析 JSON 字符串为 JsonNode 对象
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            result = jsonNode.get(nodeName).asText();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*public void saveMarkdownAsFile(String markdownContent, String filePath) throws IOException {
        Parser parser = Parser.builder().build();
        HtmlRenderer renderer = HtmlRenderer.builder().build();

        // 将Markdown转换为HTML
        String htmlContent = renderer.render(parser.parse(markdownContent));

        // 保存HTML到本地文件
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(htmlContent);
        }
    }*/


}
